package com.hboxs.asl.controller.asl.member;

import com.hboxs.asl.FileInfo;
import com.hboxs.asl.Message;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.service.FileService;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.util.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller - 图片上传
 */
@Controller("aslImageUploadController")
@RequestMapping("/m/image")
public class ImageUploadControl extends BaseController {

    @Resource(name = "fileServiceImpl")
    private FileService fileService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;

    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
    public void upload(MultipartFile file, HttpServletResponse response) {
        Map<String, Object> data = new HashMap<String, Object>();
        if (!fileService.isValid(FileInfo.FileType.image, file)) {
            data.put("message", Message.warn("admin.upload.invalid"));
        } else {
            String url = fileService.upload(FileInfo.FileType.image, file, false, memberService.getCurrent().getId().toString());
            if (url == null) {
                data.put("message", Message.warn("admin.upload.error"));
            } else {
                data.put("message", SUCCESS_MESSAGE);
                data.put("url", url);
            }
        }
        try {
            response.setContentType("text/html; charset=UTF-8");
            JsonUtils.writeValue(response.getWriter(), data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
